<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>火车管理 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../css/admin.css" rel="stylesheet">
</head>
<body>
    <!-- 导航栏 -->    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/admin/dashboard.html">
                <img src="/images/logo.jpeg" alt="Logo" class="admin-logo d-inline-block align-text-top">
                <i class="fas fa-train me-2"></i>列车车次管理系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/dashboard.html">
                            <i class="fas fa-tachometer-alt me-1"></i>仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/users.html">
                            <i class="fas fa-users me-1"></i>用户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/stations.html">
                            <i class="fas fa-map-marker-alt me-1"></i>车站管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/admin/trains.html">
                            <i class="fas fa-train me-1"></i>火车管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/routes.html">
                            <i class="fas fa-route me-1"></i>线路管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/schedules.html">
                            <i class="fas fa-calendar-alt me-1"></i>班次管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/tickets.html">
                            <i class="fas fa-ticket-alt me-1"></i>票务管理
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/profile.html">个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <!-- 页面标题 -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-train me-2"></i>火车管理</h2>
                    <div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#trainModal" onclick="showAddTrainModal()">
                            <i class="fas fa-plus me-1"></i>添加火车
                        </button>
                        <button class="btn btn-success" onclick="exportToCSV()">
                            <i class="fas fa-download me-1"></i>导出数据
                        </button>
                    </div>
                </div>

                <!-- 搜索和过滤器 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <label for="searchTrainNumber" class="form-label">车次号</label>
                                <input type="text" class="form-control" id="searchTrainNumber" placeholder="输入车次号">
                            </div>
                            <div class="col-md-3">
                                <label for="filterTrainType" class="form-label">列车类型</label>
                                <select class="form-select" id="filterTrainType">
                                    <option value="">全部类型</option>
                                    <option value="G">高速动车组(G)</option>
                                    <option value="D">动车组(D)</option>
                                    <option value="C">城际动车组(C)</option>
                                    <option value="K">快速列车(K)</option>
                                    <option value="T">特快列车(T)</option>
                                    <option value="Z">直达特快(Z)</option>
                                    <option value="普通">普通列车</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="filterStatus" class="form-label">状态</label>
                                <select class="form-select" id="filterStatus">
                                    <option value="">全部状态</option>
                                    <option value="正常">正常</option>
                                    <option value="停运">停运</option>
                                    <option value="维修">维修</option>
                                </select>
                            </div>
                            <div class="col-md-3 d-flex align-items-end">
                                <button class="btn btn-primary me-2" onclick="searchTrains()">
                                    <i class="fas fa-search me-1"></i>搜索
                                </button>
                                <button class="btn btn-secondary" onclick="resetFilters()">
                                    <i class="fas fa-undo me-1"></i>重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 火车列表 -->
                <div class="card">
                    <div class="card-body">
                        <div id="loadingSpinner" class="text-center" style="display: none;">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>车次号</th>
                                        <th>列车类型</th>
                                        <th>总座位数</th>
                                        <th>硬座</th>
                                        <th>软座</th>
                                        <th>硬卧</th>
                                        <th>软卧</th>
                                        <th>商务座</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="trainsTableBody">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="分页导航">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页按钮将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑火车模态框 -->
    <div class="modal fade" id="trainModal" tabindex="-1" aria-labelledby="trainModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="trainModalLabel">添加火车</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="trainForm">
                        <input type="hidden" id="trainId">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="trainNumber" class="form-label">车次号 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="trainNumber" required>
                                    <div class="form-text">例如：G123, D456, K789</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="trainType" class="form-label">列车类型 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="trainType" required>
                                        <option value="">请选择类型</option>
                                        <option value="G">高速动车组(G)</option>
                                        <option value="D">动车组(D)</option>
                                        <option value="C">城际动车组(C)</option>
                                        <option value="K">快速列车(K)</option>
                                        <option value="T">特快列车(T)</option>
                                        <option value="Z">直达特快(Z)</option>
                                        <option value="普通">普通列车</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="hardSeatCount" class="form-label">硬座数量</label>
                                    <input type="number" class="form-control" id="hardSeatCount" min="0" value="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="softSeatCount" class="form-label">软座数量</label>
                                    <input type="number" class="form-control" id="softSeatCount" min="0" value="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="hardSleeperCount" class="form-label">硬卧数量</label>
                                    <input type="number" class="form-control" id="hardSleeperCount" min="0" value="0">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="softSleeperCount" class="form-label">软卧数量</label>
                                    <input type="number" class="form-control" id="softSleeperCount" min="0" value="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="businessSeatCount" class="form-label">商务座数量</label>
                                    <input type="number" class="form-control" id="businessSeatCount" min="0" value="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="trainStatus" class="form-label">状态</label>
                                    <select class="form-select" id="trainStatus">
                                        <option value="正常">正常</option>
                                        <option value="停运">停运</option>
                                        <option value="维修">维修</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="totalSeats" class="form-label">总座位数</label>
                            <input type="number" class="form-control" id="totalSeats" readonly>
                            <div class="form-text">自动计算各座位类型的总和</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveTrain()">
                        <i class="fas fa-save me-1"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除火车 <strong id="deleteTrainNumber"></strong> 吗？</p>
                    <p class="text-danger">此操作不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                        <i class="fas fa-trash me-1"></i>删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../js/admin.js"></script>
    <script>
        let currentPage = 1;
        let totalPages = 1;
        let deleteTrainId = null;

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAdminAuth();
            loadTrains();
            
            // 自动计算总座位数
            const seatInputs = ['hardSeatCount', 'softSeatCount', 'hardSleeperCount', 'softSleeperCount', 'businessSeatCount'];
            seatInputs.forEach(id => {
                document.getElementById(id).addEventListener('input', calculateTotalSeats);
            });
        });

        // 加载火车列表
        async function loadTrains(page = 1) {
            try {
                showLoading(true);
                const searchTrainNumber = document.getElementById('searchTrainNumber').value;
                const filterTrainType = document.getElementById('filterTrainType').value;
                const filterStatus = document.getElementById('filterStatus').value;

                let url = `/api/trains?page=${page - 1}&size=10`;
                
                if (searchTrainNumber) {
                    url += `&trainNumber=${encodeURIComponent(searchTrainNumber)}`;
                }
                if (filterTrainType) {
                    url += `&trainType=${encodeURIComponent(filterTrainType)}`;
                }
                if (filterStatus) {
                    url += `&status=${encodeURIComponent(filterStatus)}`;
                }

                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载火车列表失败');
                }
                
                const data = await response.json();
                displayTrains(data.content || data);
                
                if (data.totalPages) {
                    totalPages = data.totalPages;
                    currentPage = page;
                    updatePagination();
                }
            } catch (error) {
                console.error('加载火车列表失败:', error);
                showAlert('加载火车列表失败', 'danger');
            } finally {
                showLoading(false);
            }
        }

        // 显示火车列表
        function displayTrains(trains) {
            const tbody = document.getElementById('trainsTableBody');
            
            if (!trains || trains.length === 0) {
                tbody.innerHTML = '<tr><td colspan="11" class="text-center">暂无数据</td></tr>';
                return;
            }

            tbody.innerHTML = trains.map(train => `
                <tr>
                    <td><strong>${train.trainNumber}</strong></td>
                    <td><span class="badge bg-info">${getTrainTypeLabel(train.trainType)}</span></td>
                    <td>${train.totalSeats || 0}</td>
                    <td>${train.hardSeatCount || 0}</td>
                    <td>${train.softSeatCount || 0}</td>
                    <td>${train.hardSleeperCount || 0}</td>
                    <td>${train.softSleeperCount || 0}</td>
                    <td>${train.businessSeatCount || 0}</td>
                    <td><span class="badge ${getStatusBadgeClass(train.status)}">${train.status}</span></td>
                    <td>${formatDateTime(train.createdAt)}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="showEditTrainModal(${train.id})" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="showDeleteModal(${train.id}, '${train.trainNumber}')" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 获取列车类型标签
        function getTrainTypeLabel(type) {
            const typeMap = {
                'G': '高速动车组(G)',
                'D': '动车组(D)',
                'C': '城际动车组(C)',
                'K': '快速列车(K)',
                'T': '特快列车(T)',
                'Z': '直达特快(Z)',
                '普通': '普通列车'
            };
            return typeMap[type] || type;
        }

        // 获取状态徽章样式
        function getStatusBadgeClass(status) {
            switch (status) {
                case '正常': return 'bg-success';
                case '停运': return 'bg-danger';
                case '维修': return 'bg-warning';
                default: return 'bg-secondary';
            }
        }

        // 计算总座位数
        function calculateTotalSeats() {
            const hardSeat = parseInt(document.getElementById('hardSeatCount').value) || 0;
            const softSeat = parseInt(document.getElementById('softSeatCount').value) || 0;
            const hardSleeper = parseInt(document.getElementById('hardSleeperCount').value) || 0;
            const softSleeper = parseInt(document.getElementById('softSleeperCount').value) || 0;
            const businessSeat = parseInt(document.getElementById('businessSeatCount').value) || 0;
            
            const total = hardSeat + softSeat + hardSleeper + softSleeper + businessSeat;
            document.getElementById('totalSeats').value = total;
        }

        // 显示添加火车模态框
        function showAddTrainModal() {
            document.getElementById('trainModalLabel').textContent = '添加火车';
            document.getElementById('trainForm').reset();
            document.getElementById('trainId').value = '';
            document.getElementById('trainStatus').value = '正常';
            calculateTotalSeats();
        }

        // 显示编辑火车模态框
        async function showEditTrainModal(trainId) {
            try {
                const response = await fetch(`/api/trains/${trainId}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取火车信息失败');
                }
                
                const train = await response.json();
                
                document.getElementById('trainModalLabel').textContent = '编辑火车';
                document.getElementById('trainId').value = train.id;
                document.getElementById('trainNumber').value = train.trainNumber;
                document.getElementById('trainType').value = train.trainType;
                document.getElementById('hardSeatCount').value = train.hardSeatCount || 0;
                document.getElementById('softSeatCount').value = train.softSeatCount || 0;
                document.getElementById('hardSleeperCount').value = train.hardSleeperCount || 0;
                document.getElementById('softSleeperCount').value = train.softSleeperCount || 0;
                document.getElementById('businessSeatCount').value = train.businessSeatCount || 0;
                document.getElementById('trainStatus').value = train.status;
                calculateTotalSeats();
                
                new bootstrap.Modal(document.getElementById('trainModal')).show();
            } catch (error) {
                console.error('获取火车信息失败:', error);
                showAlert('获取火车信息失败', 'danger');
            }
        }

        // 保存火车
        async function saveTrain() {
            try {
                const form = document.getElementById('trainForm');
                const formData = new FormData(form);
                
                const trainData = {
                    trainNumber: document.getElementById('trainNumber').value,
                    trainType: document.getElementById('trainType').value,
                    hardSeatCount: parseInt(document.getElementById('hardSeatCount').value) || 0,
                    softSeatCount: parseInt(document.getElementById('softSeatCount').value) || 0,
                    hardSleeperCount: parseInt(document.getElementById('hardSleeperCount').value) || 0,
                    softSleeperCount: parseInt(document.getElementById('softSleeperCount').value) || 0,
                    businessSeatCount: parseInt(document.getElementById('businessSeatCount').value) || 0,
                    totalSeats: parseInt(document.getElementById('totalSeats').value) || 0,
                    status: document.getElementById('trainStatus').value
                };

                // 验证必填字段
                if (!trainData.trainNumber || !trainData.trainType) {
                    showAlert('请填写所有必填字段', 'warning');
                    return;
                }

                const trainId = document.getElementById('trainId').value;
                const url = trainId ? `/api/trains/${trainId}` : '/api/trains';
                const method = trainId ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify(trainData)
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '保存失败');
                }

                showAlert(trainId ? '火车更新成功' : '火车添加成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('trainModal')).hide();
                loadTrains(currentPage);
            } catch (error) {
                console.error('保存火车失败:', error);
                showAlert(error.message || '保存火车失败', 'danger');
            }
        }

        // 显示删除模态框
        function showDeleteModal(trainId, trainNumber) {
            deleteTrainId = trainId;
            document.getElementById('deleteTrainNumber').textContent = trainNumber;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }

        // 确认删除
        async function confirmDelete() {
            try {
                const response = await fetch(`/api/trains/${deleteTrainId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (!response.ok) {
                    throw new Error('删除失败');
                }

                showAlert('火车删除成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                loadTrains(currentPage);
            } catch (error) {
                console.error('删除火车失败:', error);
                showAlert('删除火车失败', 'danger');
            }
        }

        // 搜索火车
        function searchTrains() {
            currentPage = 1;
            loadTrains();
        }

        // 重置过滤器
        function resetFilters() {
            document.getElementById('searchTrainNumber').value = '';
            document.getElementById('filterTrainType').value = '';
            document.getElementById('filterStatus').value = '';
            currentPage = 1;
            loadTrains();
        }

        // 导出到CSV
        function exportToCSV() {
            const csvContent = generateCSVContent();
            downloadCSV(csvContent, 'trains.csv');
        }

        function generateCSVContent() {
            const headers = ['车次号', '列车类型', '总座位数', '硬座', '软座', '硬卧', '软卧', '商务座', '状态', '创建时间'];
            let csv = headers.join(',') + '\n';
            
            const rows = document.querySelectorAll('#trainsTableBody tr');
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                if (cells.length > 1) {
                    const rowData = [
                        cells[0].textContent.trim(),
                        cells[1].textContent.trim(),
                        cells[2].textContent.trim(),
                        cells[3].textContent.trim(),
                        cells[4].textContent.trim(),
                        cells[5].textContent.trim(),
                        cells[6].textContent.trim(),
                        cells[7].textContent.trim(),
                        cells[8].textContent.trim(),
                        cells[9].textContent.trim()
                    ];
                    csv += rowData.join(',') + '\n';
                }
            });
            
            return csv;
        }

        function downloadCSV(content, filename) {
            const blob = new Blob(['\ufeff' + content], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 更新分页
        function updatePagination() {
            const pagination = document.getElementById('pagination');
            let paginationHTML = '';

            // 上一页
            paginationHTML += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadTrains(${currentPage - 1})" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `;

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage || i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    paginationHTML += `
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadTrains(${i})">${i}</a>
                        </li>
                    `;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    paginationHTML += '<li class="page-item disabled"><a class="page-link">...</a></li>';
                }
            }

            // 下一页
            paginationHTML += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadTrains(${currentPage + 1})" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `;

            pagination.innerHTML = paginationHTML;
        }

        // 显示加载状态
        function showLoading(show) {
            document.getElementById('loadingSpinner').style.display = show ? 'block' : 'none';
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 显示提示信息
        function showAlert(message, type) {
            // 使用Bootstrap的alert组件显示消息
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.top = '20px';
            alertDiv.style.right = '20px';
            alertDiv.style.zIndex = '9999';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            // 3秒后自动隐藏
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 3000);
        }
    </script>
</body>
</html>
